package org.dftproject.genesis.data.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.dftproject.genesis.data.IAttribute;
import org.dftproject.genesis.data.IEntity;

public class EntityImpl implements IEntity {
	
	private final Map<String, Set<IAttribute>> attributesByName = new HashMap<String, Set<IAttribute>>();

	public Set<IAttribute> getAttributes() {
		Set<IAttribute> results = new HashSet<IAttribute>();
		
		for (Set<IAttribute> attributes : attributesByName.values())
			results.addAll(attributes);
		
		return Collections.unmodifiableSet(results);
	}
	
	public Set<IAttribute> getAttributes(String name) {
		Set<IAttribute> attributes = attributesByName.get(name);
		if (attributes != null)
			return Collections.unmodifiableSet(attributes);
		return Collections.emptySet();
	}
	
	public void addAttribute(IAttribute attribute) {
		String name = attribute.getName();
		Set<IAttribute> attributes = attributesByName.get(name);
		if (attributes == null) {
			attributes = new HashSet<IAttribute>();
			attributesByName.put(name, attributes);
		}
		attributes.add(attribute);
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("Entity(");
		Iterator<IAttribute> it = getAttributes().iterator();
		while (it.hasNext()) {
			sb.append(it.next().toString());
			if (it.hasNext())
				sb.append(", ");
		}
		sb.append(")");
		return sb.toString();
	}

	public Set<IEntity> getEntities() {
		Set<IEntity> entities = new HashSet<IEntity>();
		entities.add(this);
		return entities;
	}

	public boolean sameAs(IEntity other) {
		return other.getEntities().contains(this);
	}

}
